from http.server import HTTPServer, BaseHTTPRequestHandler
from urllib.parse import parse_qs
from calculate_chunk_sha256 import ChunkHashCalculator
import time
import hashlib


main_dir = r'.'


# 全局变量存储 ChunkHashCalculator 实例
calculator = None

# 内部hash状态
inner_hash_status = b''

class RandomNumberHandler(BaseHTTPRequestHandler):
    """处理 HTTP 请求的处理器类"""
    
    def do_GET(self):
        """处理 GET 请求"""
        # 解析 URL 和查询参数
        path = self.path.split('?')[0]
        query = parse_qs(self.path.split('?')[1]) if '?' in self.path else {}
        
        if path == '/random':
            self._handle_random(query)
        elif path == '/health':
            self._handle_health()
        else:
            self._handle_not_found()
    
    def _handle_random(self, query):
        """处理 /random 请求
        
        Args:
            query: URL 查询参数字典
        """
        global inner_hash_status  # 在函数开始处声明全局变量
        
        if calculator is None:
            self._send_error(500)
            return
        
        try:
            # 获取长度参数，默认为32（SHA256的长度）
            length = 32
            if 'len' in query:
                try:
                    length = int(query['len'][0])
                    if length <= 0 or length > 32:
                        self._send_error(400)
                        return
                except ValueError:
                    self._send_error(400)
                    return
            
            # 获取下一个哈希值
            hash_value = calculator.calculate_next_hash()
            if hash_value is None:
                self._send_error(500)
                return
            
            # 获取当前时间戳（纳秒精度）
            current_time = str(time.time_ns()).encode('ascii')
            
            # 拼接数据并计算新的哈希值
            combined_data = hash_value + current_time + inner_hash_status
            new_hash = hashlib.sha256(combined_data).digest()
            
            # 更新内部哈希状态
            inner_hash_status = new_hash
            
            # 截取指定长度的哈希值
            result = new_hash[:length]
            self._send_text_response(result.hex())
            
        except Exception as e:
            print(f"生成随机数时发生错误: {e}")
            self._send_error(500)
    
    def _handle_health(self):
        """处理 /health 请求"""
        status = "healthy" if calculator is not None else "unhealthy"
        self._send_text_response(status)
    
    def _handle_not_found(self):
        """处理 404 错误"""
        self._send_error(404)
    
    def _send_text_response(self, text):
        """发送文本响应"""
        self.send_response(200)
        self.send_header('Content-type', 'text/plain; charset=utf-8')
        self.end_headers()
        self.wfile.write(text.encode('utf-8'))
    
    def _send_error(self, code):
        """发送错误响应，只返回状态码，不返回任何内容"""
        self.send_response(code)
        self.end_headers()

def main():
    """启动 HTTP 服务"""
    global calculator
    
    try:
        # 初始化 ChunkHashCalculator
        calculator = ChunkHashCalculator(
            directory=main_dir,
            chunk_size=3793,
            max_files=1024
        )
        
        # 创建并启动服务器
        server_address = ('0.0.0.0', 8120)
        httpd = HTTPServer(server_address, RandomNumberHandler)
        print(f"启动服务器在 http://{server_address[0]}:{server_address[1]}")
        httpd.serve_forever()
        
    except Exception as e:
        print(f"服务器启动失败: {e}")
        raise

if __name__ == "__main__":
    main() 